package cn.tx.common.concurrent;

/**
 * @author: 可乐加糖
 * @create: 2023-03-21 16:37
 * @Description: 线程池拒绝策略
 */

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j

public class ThreadPoolRejectedT2 {

    public static void main(String[] args) throws Exception{

        int corePoolSize = 5;

        int maximumPoolSize = 10;

        long keepAliveTime = 5;

        BlockingQueue workQueue = new LinkedBlockingQueue(10);

        //默认的 defaultHandler ，也即 AbortPolicy 策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        RejectedExecutionHandler handler2 = new ThreadPoolExecutor.CallerRunsPolicy();
        RejectedExecutionHandler handler3 = new ThreadPoolExecutor.DiscardPolicy();
        RejectedExecutionHandler handler4 = new ThreadPoolExecutor.DiscardOldestPolicy();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,TimeUnit.SECONDS,workQueue,handler);

        for(int i=0; i<100; i++) {

            try {

                executor.execute(new Thread(() -> log.info(Thread.currentThread().getName() + " is running")));

            } catch (Exception e) {

                log.error(e.getMessage());

            }

        }

        executor.shutdown();

    }

}